package com.team.client_server;

import com.team.communication.ClientRequest;

public class ClientMessage extends Message {

	private ClientRequest request;
	
	public ClientMessage(String message) {
		super(message);
	}


	public ClientMessage(MessageHeader em, int id, int seq, String[] param, ClientRequest request) {
		super(em, id, seq);
		if (param == null){
			param = new String[0];
		}
		if(request == null){
			request = ClientRequest.INITCON;
		}
		setParam(param);
		this.request = request;
	}

	
	public String createMessage(){
		String parametre = ":";
		for(int i=0;i<this.param.length;i++){
			parametre = parametre+this.param[i]+";";
		}
		
		return "|type="+messageHeader+"|id="+id+"|seq="+sequenceNumber+"|req="+request.getDescription()+"|par="+param.length+parametre;
	}
	
	protected void parseMessage(String message) {
		
		
		this.messageHeader = MessageHeader.valueOf(subMessage("|type=","|id=",6,message));
		//System.out.println(message.substring(position_debut+6, position_fin));
		
		this.id = Integer.parseInt(subMessage("|id=","|seq=",4,message));
		//System.out.println(message.substring(position_debut+4, position_fin));
		
		
		this.sequenceNumber = Integer.parseInt(subMessage("|seq=","|req=",5,message));
		//System.out.println(message.substring(position_debut+5, position_fin));
		this.request = ClientRequest.getClientRequestFromDescription(subMessage("|req=","|par=",5,message));
		//System.out.println(message.substring(position_debut+5, position_fin));
		
		
		//this.para = EnteteMessage.entete(message.substring(position_debut+7, position_fin));
		//System.out.println(message.substring(position_debut+5, position_fin));
		
		
		
		int lenght = Integer.parseInt(subMessage("|par=",":",5,message));
		
		String[] tab = new String[lenght];
		
		
		int position_fin = message.indexOf(":");
		int position_debut = position_fin;
		
		for(int i=0;i<lenght;i++){
			message = message.substring(position_fin+1);
			position_fin = message.indexOf(";");
			if (position_debut == -1 || position_fin == -1){
				//throw error messageException
			}
			tab[i] = message.substring(0, position_fin);
			//System.out.println(message.substring(0, position_fin));
			
		}
		
		this.param = tab;
		
	}


	public ClientRequest getRequest() {
		return request;
	}


	public void setRequest(ClientRequest request) {
		this.request = request;
	}
	
}
